package io.fredia.common.utils;

import com.alibaba.fastjson.JSONObject;

import io.fredia.common.web.Md5Utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Formatter;
import java.util.UUID;

public class WeixinUtils
{
    public static String getAccessToken()
    {
        String appId = "wxf7e06152b51e81e7";//GlobalConstant.getString("wechat.appid");
        String appSecret = "273bc10622f52be04371ef6d2943250f";//GlobalConstant.getString("wechat.appSecret");
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String jsonText = HttpClientUtils.httpGetRequest(url);
        JSONObject jsonObject =  (JSONObject)JSONObject.parse(jsonText);
        return jsonObject.getString("access_token");
    }

    public static String getTicket(String access_token)
    {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";

        String jsonText = HttpClientUtils.httpGetRequest(url);
        JSONObject jsonObject =  (JSONObject)JSONObject.parse(jsonText);

        return jsonObject.getString("ticket");
    }

    public static String getSignature(String ticket, String nonce, String timestamp, String url) {
        String  str = "jsapi_ticket=" + ticket + "&noncestr=" + nonce + "&timestamp=" + timestamp + "&url=" + url;

        MessageDigest crypt = null;
        try {
            crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(str.getBytes("UTF-8"));

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return byteToHex(crypt.digest());
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    /**
     * 创建时间戳
     *
     * @return
     */
    public static String createTimestamp() {
        return Long.toString(new Date().getTime()).substring(0, 10);
    }

    /**
     * 创建随机字符
     *
     * @return
     */
    public static String createNonceStr() {
        return RandomUtils.randomNumbers(10);
    }
}
